<template>
  <div>
    <div v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)" id="map" ref="bmap"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "福州理工学院",
      loading: true,
    };
  },
  mounted() {
    this.initMap();
    this.setPlace();

    this.loading = false;
  },
  methods: {
    initMap() {
      this.map = new BMap.Map(this.$refs.bmap);
      let point = new BMap.Point(119.330221, 26.047125);
      this.map.centerAndZoom(point, 17);
      this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
      this.map.addControl(new BMap.NavigationControl());
    },

    setPlace() {
      this.local = new BMap.LocalSearch(this.map, {
        onSearchComplete: this.searchPlace,
      });

      this.local.search(this.keyWords);
    },
    searchPlace() {
      if (this.local.getResults() != undefined) {
        this.map.clearOverlays(); //清除地图上所有覆盖物
        if (this.local.getResults().getPoi(0)) {
          let point = this.local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
          this.map.centerAndZoom(point, 18);
          this.handleMarker(this, point);
          // console.log("经度：" + point.lng + "--" + "纬度" + point.lat);
          this.latitude = point.lat;
          this.longitude = point.lng;
        } else {
          this.$message.error("未匹配到地点!");
        }
      } else {
        this.$message.error("未找到搜索结果!");
      }
    },
    // 设置标注
    handleMarker(obj, point) {
      obj.mk = new BMap.Marker(point);
      obj.map.addOverlay(obj.mk);
      obj.mk.enableDragging(); // 可拖拽
      obj.mk.addEventListener("dragend", function (e) {
        // 监听标注的拖拽，获取拖拽后的经纬度
        this.latitude = point.lat;
        this.longitude = point.lng;
      });

      obj.map.panTo(point);
    },
  },
};
</script>
<style lang="less" scoped>
#map {
  width: 100%;
  height: 50vh;
  touch-action: none;
}

// 去除版权信息
/deep/.BMap_cpyCtrl {
  display: none !important;
}

/deep/.anchorBL {
  display: none !important;
}
</style>
